//
//  StatusListViewModel.m
//  weibo-OC
//
//  Created by diyuyma on 16/3/24.
//  Copyright © 2016年 zhangkaiyun. All rights reserved.
//

#import "StatusListViewModel.h"
#import "UserAccountViewModel.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "Status.h"
#import "SDWebImageManager.h"

@implementation StatusListViewModel

//MARK: 加载微博首页数据
- (void)loadData:(void(^)(NSMutableArray *array))finished WithSince_id: (NSInteger)since_id WithMax_id: (NSInteger)max_id {
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    NSString *token = [[UserAccountViewModel alloc] init].token;
    if (token == nil) {
        [SVProgressHUD showErrorWithStatus:@"您暂未登陆"];
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:token forKey:@"access_token"];

    NSString *since_Id = [NSString stringWithFormat:@"%ld", since_id];
    NSString *max_Id = [NSString stringWithFormat:@"%ld", max_id - 1];
    //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    if (since_id > 0) {
        //添加since_id 对应键值
        [parameters setObject:since_Id forKey:@"since_id"];
    }
    
    //	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    if (max_id > 0) {
        [parameters setObject:max_Id forKey:@"max_id"];
    }
    [[NetworkTools sharedTools] requestJsonDict:GET WithUrlString:urlString WithParameters:parameters WithFinished:^(NSDictionary *result, NSError *error) {
        
        if (error != nil) {
            finished(nil);
            return ;
        }
        NSArray *array = result[@"statuses"];
        NSMutableArray *list = [[NSMutableArray alloc] init];
        // 遍历数组
        for (NSDictionary *item in array) {
            // 字典转模型
            Status *s = [[Status alloc] initWithDict:item];
            // 添加微博对象
            [list addObject:s];
        }
        
        // 完成单张图片的缓存
        [[[StatusListViewModel alloc] init] cacheStatusImage:list WithFinished:finished];
//        // 完成回调
//        finished(list);
    }];
}


- (void)cacheStatusImage: (NSMutableArray *)array WithFinished: (void(^)(NSMutableArray *array))finished {
    // 缓存单张图片
    if (array.count == 0) {
        // 完成回调
        finished(nil);
        return;
    }
    
    // 创建群组
    dispatch_group_t group = dispatch_group_create();
    // 遍历模型数组
    for (Status *s in array) {
        NSArray *imageurls  = s.pictureURLs;
            // 如果不是单张图片
            if (imageurls.count != 1) {
                continue;
            }
            // 一定是单张图片
            for (NSURL *url in imageurls) {
                //开始下载图片
                //异步加载图片的开始
                //向群组中添加异步任务
                dispatch_group_enter(group);
                [[SDWebImageManager sharedManager] downloadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                    //异步任务离开群组
                    dispatch_group_leave(group);
                }];
        }
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        //在主线程完成回调
        finished(array);
    });
}
@end
